<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>litegl.js: mesh formats example</title>
	<link rel="stylesheet" type="text/css" href="style.css" />
	<style type='text/css'>
		html, body { background-color: #DDD; margin: 0; padding: 0; width: 100%; height: 100%;}
		canvas { cursor: move; }
		.tools {
			position: fixed;
			top: 10px;
			left: 10px;
		}
		button {
			border: 0;
			border-radius: 10px;
			font-size: 20px;
			padding: 10px;
			background-color: #334;
		}
	</style>
	<script type="text/javascript" src="../external/gl-matrix.js"></script>
	<script type="text/javascript" src="../external/wbin.js"></script>
	<script type="text/javascript" src="../build/litegl.js"></script>
	<script type="text/javascript">

	var mesh = null;
	
	function init()
	{
		//create the rendering context
		var container = document.body;

		var gl = GL.create({width: container.offsetWidth, height: container.offsetHeight});
		container.appendChild(gl.canvas);
		gl.animate();

		//camera settings
		var cam_pos = [0,100,250];
		var cam_center = [0,100,0];

		//adjust camera to mesh bounding
		function adjustCameraToBounding( mesh ){
			cam_center = BBox.getCenter( mesh.bounding );
			var r = BBox.getRadius( mesh.bounding );
			cam_pos = vec3.add( cam_pos, cam_center, [0,r*0.5, r*3] );
		}

		//build the mesh
		mesh = GL.Mesh.fromURL( "girl.wbin", adjustCameraToBounding ); //load from URL

		//create basic matrices for cameras and transformation
		var proj = mat4.create();
		var view = mat4.create();
		var model = mat4.create();
		var mvp = mat4.create();
		var temp = mat4.create();

		//get mouse actions to drag the mesh
		gl.captureMouse();
		gl.onmousemove = function(e)
		{
			if(e.dragging)
			{
				mat4.rotateY(model,model,e.deltax * 0.01);
				var r = BBox.getRadius( mesh.bounding );
				cam_pos[2] += e.deltay * r * 0.01;
			}
		}

		//set the camera position
		mat4.perspective(proj, 45 * DEG2RAD, gl.canvas.width / gl.canvas.height, 0.1, 1000);

		//basic phong shader
		var shader = new Shader('\
				precision highp float;\
				attribute vec3 a_vertex;\
				attribute vec3 a_normal;\
				varying vec3 v_normal;\
				uniform mat4 u_mvp;\
				uniform mat4 u_model;\
				void main() {\
					v_normal = (u_model * vec4(a_normal,0.0)).xyz;\
					gl_Position = u_mvp * vec4(a_vertex,1.0);\
				}\
				', '\
				precision highp float;\
				varying vec3 v_normal;\
				uniform vec3 u_lightvector;\
				uniform vec4 u_camera_position;\
				uniform vec4 u_color;\
				void main() {\
				  vec3 N = normalize(v_normal);\
				  //fake half light\n\
				  float NdotL = dot(u_lightvector,N) * 0.5 + 0.5;\
				  NdotL *= NdotL;\
				  gl_FragColor = u_color * max(0.0, NdotL);\
				}\
			');


		//generic gl flags and settings
		gl.clearColor(0.1,0.1,0.1,1);
		gl.enable( gl.DEPTH_TEST );

		//rendering loop
		gl.ondraw = function()
		{
			gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
			mat4.lookAt(view, cam_pos, cam_center, [0,1,0]);

			//create modelview and projection matrices
			mat4.multiply(temp,view,model);
			mat4.multiply(mvp,proj,temp);

			//render mesh using the shader
			if(mesh)
				shader.uniforms({
					u_color: [1,1,1,1],
					u_lightvector: vec3.normalize(vec3.create(),[1,1,1]),
					u_camera_position: cam_pos,
					u_model: model,
					u_mvp: mvp
				}).draw(mesh);
		};

		//Allows to DRAG AND DROP files
		var dropbox = document.body;
		dropbox.addEventListener("dragenter", onDragEvent, false);
		function onDragEvent(evt)
		{
			for(var i in evt.dataTransfer.types)
				if(evt.dataTransfer.types[i] == "Files")
				{
					if(evt.type != "dragover") console.log("Drag event: " + evt.type);
					evt.stopPropagation();
					evt.preventDefault();

					dropbox.addEventListener("dragexit", onDragEvent, false);
					dropbox.addEventListener("dragover", onDragEvent, false);
					dropbox.addEventListener("drop", onDrop, false);
				}
		}

		function onDrop(evt)
		{
			dropbox.removeEventListener("dragexit", onDragEvent, false);
			dropbox.removeEventListener("dragover", onDragEvent, false);
			dropbox.removeEventListener("drop", onDrop, false);
			//load file in memory
			onFileDrop(evt);
		}

		function onFileDrop(evt)
		{
			evt.stopPropagation();
			evt.preventDefault();

			var files = evt.dataTransfer.files;
			var count = files.length;
			
			for(var i=0; i < files.length; i++)
			{
				var file = files[i];
				var reader = new FileReader();
				var index = file.name.lastIndexOf(".");
				var extension = file.name.substr(index+1);
				reader.onload = function(e) { 
					var data = e.target.result;
					mesh.parse( data, extension );
					adjustCameraToBounding(mesh);
				};
				if(extension == "wbin")
				    reader.readAsArrayBuffer(file);
				else
				    reader.readAsText(file);
			}
		}

		window.download = function(format)
		{
			var file = null;
			if(format == "wbin")
				file = mesh.encode("wbin");
			else
				file = mesh.encode("obj");
			var url = URL.createObjectURL( new Blob([file]) );
			var element = document.createElement("a");
			element.setAttribute('href', url);
			element.setAttribute('download', "mesh." + format );
			element.style.display = 'none';
			document.body.appendChild(element);
			element.click();
			document.body.removeChild(element);
		}
	}	
	
	</script>
</head>
<body>
	<div class="tools">
		<button onclick="download('wbin');">Download as WBIN</button><button onclick="download('obj');">Download as OBJ</button> Drag and drop a mesh in OBJ or WBin format...
	</div>
	<script>init();</script>
</body>
</html>


